<template>
  <div class="terminal-container">
    <!-- 终端头部 -->
    <TerminalHeader :shellInfo="shellInfo" />

    <!-- 终端内容区 -->
    <div class="terminal-content" ref="terminalContent">
      <TerminalOutputLine :outputLines="outputLines" />
      <div class="input-line">
        <span class="prompt">{{ prompt }}</span>
        <el-input
          v-model="currentInput"
          ref="commandInput"
          @keydown.enter="handleEnter"
          @keydown.arrow-up="handleHistoryUp"
          @keydown.arrow-down="handleHistoryDown"
          @keydown.tab="handleTabComplete"
          class="command-input"
          autocomplete="off"
          spellcheck="false"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import TerminalHeader from './components/TerminalHeader.vue'
import TerminalOutputLine from './components/TerminalOutputLine.vue'
import { ref, onMounted, nextTick, watch } from 'vue'
import { useElementSize } from '@vueuse/core'
// 1. 先声明元素 ref（关键：在使用前声明）
const terminalContent = ref<HTMLDivElement | null>(null) // 正确初始化：null

const commandInput = ref<HTMLInputElement>()
// 终端状态
const outputLines = ref<string[]>([])
const currentInput = ref('')
const commandHistory = ref<string[]>([])
const historyIndex = ref(-1)
const shellInfo = ref('Terminal')
const prompt = ref('$ ')
// 2. 获取元素尺寸（使用 useElementSize + 元素 ref）
const { width, height } = useElementSize(terminalContent) //useWindowSize获取window尺寸// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (terminalContent.value) {
      terminalContent.value.scrollTop = terminalContent.value.scrollHeight
    }
  })
}
// 窗口大小变化时滚动到底部
watch([width, height], scrollToBottom)
// 组件挂载时初始化
onMounted(() => {
  initTerminal()
  // 聚焦输入框
  nextTick(() => {
    commandInput.value?.focus()
  })
})
// 初始化终端
const initTerminal = async () => {
  try {
    const result = await window.electronAPI.terminalStart()
    shellInfo.value = `${result.shell} (PID: ${result.pid})`
    listenEvents()
  } catch (error) {
    addOutput(
      `Error initializing terminal: ${error instanceof Error ? error.message : String(error)}`
    )
  }
}
const listenEvents = () => {
  // 监听终端输出
  window.electronAPI.terminalOutput((output) => {
    addOutput(output)
  })

  // 监听终端退出
  window.electronAPI.terminalExit((code) => {
    addOutput(`\nTerminal exited with code: ${code}`)
    prompt.value = ''
  })

  // 监听终端错误
  window.electronAPI.terminalError((error) => {
    addOutput(`\nError: ${error}`)
  })

  // 监听清屏事件
  window.electronAPI.terminalClear(() => {
    outputLines.value = []
  })
}
// 添加输出到终端
const addOutput = (output: string) => {
  // 处理换行和特殊字符
  let processedOutput = output.replace(/\n/g, '<br>').replace(/\t/g, '  ').replace(/ /g, '&nbsp;')

  // 如果有内容，添加到最后一行
  if (outputLines.value.length > 0) {
    const lastIndex = outputLines.value.length - 1
    outputLines.value[lastIndex] += processedOutput
  } else {
    outputLines.value.push(processedOutput)
  }

  // 自动滚动到底部
  scrollToBottom()
}

// 处理回车提交命令
const handleEnter = async () => {
  const command = currentInput.value.trim()
  if (!command) {
    addOutput('\n')
    currentInput.value = ''
    return
  }
  // 保存命令历史
  commandHistory.value.push(command)
  historyIndex.value = commandHistory.value.length
  // 显示命令
  addOutput(`\n${prompt.value}${command}\n`)
  // 发送命令到主进程
  await window.electronAPI.terminalSend(command)
  // 清空输入
  currentInput.value = ''
}

// 处理上箭头查看历史命令
const handleHistoryUp = (e: any) => {
  e.preventDefault()
  if (historyIndex.value > 0) {
    historyIndex.value--
    currentInput.value = commandHistory.value[historyIndex.value] || ''
  }
}

// 处理下箭头查看历史命令
const handleHistoryDown = (e: any) => {
  e.preventDefault()
  if (historyIndex.value < commandHistory.value.length - 1) {
    historyIndex.value++
    currentInput.value = commandHistory.value[historyIndex.value] || ''
  } else {
    historyIndex.value = commandHistory.value.length
    currentInput.value = ''
  }
}

// 处理Tab补全(简单实现)
const handleTabComplete = (e: any) => {
  e.preventDefault()
  // 实际应用中可以实现更复杂的命令补全逻辑
  const input = currentInput.value
  if (input) {
    // 这里只是简单示例，实际需要根据上下文提供补全
    addOutput(`\nTab completion not implemented for: ${input}`)
  }
}
</script>

<style scoped lang="scss">
.terminal-container {
  width: 100%;
  height: 400px;
  background-color: #1e1e1e;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .input-line {
    display: flex;
  }
  .terminal-content {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    white-space: pre-wrap;
    .prompt {
      color: #4ec9b0;
      margin-right: 4px;
      line-height: 32px;
    }
    ::v-deep {
      .command-input {
        .el-input__wrapper {
          padding: 0;
          box-shadow: none;
          background: transparent;
        }
      }
    }
  }
}
</style>
